import socket,select
from helpFunc import *
import uuid,json,hashlib

mySalt = serviceSaltKey.encode()
from connc import tcpRe
id = hashlib.md5(str(uuid.uuid1()).encode()).digest()
import binascii
id = binascii.hexlify(id)
ports2 = []
gSalt = randomStringDigits().encode()

while True:
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    re = structWrapper()
    re.writeArr(id)
    re.writeDouble(con_minRate)
    re.writeWord(con_pushAhead)
    re.writeWord(con_packLimit)
    re.writeArr(gSalt)
    re.writeWord(maxPortNum)    
    u ,s2 = makePack(re.data,mySalt)      
    sock.sendto(s2, (con_serverIp, servicePort))
    r = select.select([sock],[],[],timeoutTime)
    if r[0]==[]:
        sock.close()
        continue
    j = sock.recv(recLen)
    s2 = checkPackValid(j,u,mySalt)
    if not s2:
        sock.close()
        continue 
    ports = []
    st = structWrapper(s2)    
    for i in range(maxPortNum):
        ports.append(st.readWord()+65536//2)
    print ('server starts:',ports)
    ports2 = ports
    sock.close()
    break

import time

serverListenPort = ports2
rate = con_minRate
pushAhead = con_pushAhead
packLimit = con_packLimit
salt = gSalt
t = tcpRe(serverListenPort,salt)


